package com.hoas.comparedb.util;

import com.hoas.comparedb.pojo.TableChange;
import com.hoas.comparedb.pojo.TableDiffItem;

import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

public class DBCompareCollector implements Collector<TableChange, CompareReporter, CompareReporter> {

    /**
     * 初始化聚合器
     * @return
     */
    @Override
    public Supplier<CompareReporter> supplier() {
        return CompareReporter::new;
    }

    /**
     * 聚合计算
     * @return
     */
    @Override
    public BiConsumer<CompareReporter, TableChange> accumulator() {

        return (reporter, change) -> {
            reporter.setTotalCount(reporter.getTotalCount() +1);

            if (TableDiffItem.CREATE.equals(change.getTableDiff().getType())) {
                reporter.setAddCount(reporter.getAddCount() +1);
            } else if (TableDiffItem.ALTER.equals(change.getTableDiff().getType())){
                reporter.setAlterCount(reporter.getAlterCount() +1);
            }
        };
    }

    /**
     * 多流结果合并
     * @return
     */
    @Override
    public BinaryOperator<CompareReporter> combiner() {
        return (r1, r2) -> {
            CompareReporter r3 = new CompareReporter();
            r3.setTotalCount(r1.getTotalCount() + r2.getTotalCount());
            r3.setAddCount( r1.getAddCount() + r2.getAddCount());
            r3.setAlterCount( r1.getAlterCount() + r2.getAlterCount());
            r3.setDropCount( r1.getDropCount() + r2.getDropCount());
            return r3;
        };
    }

    @Override
    public Function<CompareReporter, CompareReporter> finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH));
    }
}
